package com.retoc.graduationtravel.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.retoc.graduationtravel.common.ApiRestResponse;
import com.retoc.graduationtravel.domain.Comment;
import com.retoc.graduationtravel.domain.User;
import com.retoc.graduationtravel.domain.VO.CommentVO;
import com.retoc.graduationtravel.exception.ExceptionEnum;
import com.retoc.graduationtravel.service.CommentService;
import com.retoc.graduationtravel.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping("/comment")
@RestController
public class CommentController {

    @Autowired
    CommentService commentService;

    @Autowired
    UserService userService;

    @GetMapping("/getComment")
    public ApiRestResponse<List<CommentVO>> getComment(@RequestParam("articleId") Long articleId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", articleId);
        List<Comment> list = commentService.list(queryWrapper);
        List<CommentVO> result = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Long userId = list.get(i).getUserId();
            QueryWrapper<User> qw = new QueryWrapper<>();
            qw.eq("id", userId);
            User user = userService.getOne(qw);
            CommentVO commentVO = new CommentVO();
            BeanUtils.copyProperties(list.get(i), commentVO);
            BeanUtils.copyProperties(user, commentVO);
            result.add(commentVO);
        }
        if (!result.isEmpty()) {
            return ApiRestResponse.success(result);
        } else {
            return ApiRestResponse.error(ExceptionEnum.COMMENT_FAIL);
        }
    }

    @PostMapping("/comment")
    public ApiRestResponse<Boolean> comment(@Valid @RequestBody Comment comment) {
        comment.setDate(new Date());
        boolean result = commentService.save(comment);
        if (result) {
            return ApiRestResponse.success(true);
        } else {
            return ApiRestResponse.error(ExceptionEnum.COMMENT1_FAIL);
        }
    }
}
